import "./index.less";
import loginFormView from "./index.html";
import Dialog from "../dialog/index.js";
import Utils from "../../../common/utils.js";
import IndexService from "../../../services/indexService.js";
const galleryService = new IndexService();

/**
 * 登录表单
 */
export default class LoginForm {
  constructor(isLogin, data) {
    this.body = $("body");
    this.isLogin = isLogin;
    this.data = data;
    this.disableScroll = true;
    this.viewPortSizeHeight = 0;
    this.complied = _.template(loginFormView);
    this.render();
    this.registerEvents();

  }
  registerEvents() {
    let _this = this;
    function touchMove(e) {
      e.preventDefault();
    }
    function touchMoveLogin() {
      let offY = Utils.getOffset($("#user-name")[0]).offsetY;
      window.scrollTo(0, offY - 60);
    }
    function touchEndLogin() {
      let offY = Utils.getOffset($("#user-name")[0]).offsetY;
      window.scrollTo(0, offY - 60);
      if (checkDevice() == "android") {
        document.removeEventListener('scroll', scroll);
        document.addEventListener('scroll', scroll, false);
      }
    }
    function scroll() {
      setTimeout(function () {
        let offY = Utils.getOffset($("#user-name")[0]).offsetY;
        window.scrollTo(0, offY - 60);
      }, 500);
    }
    document.addEventListener('touchmove', touchMove, false);
    let focusClassName = null;
    let focusInterval = null;
    let blurClassNameArray = [];
    //如果弹出对话框时，底层的视图就不让滚动了
    $("#user-name,#user-pwd").off().on("focus", function (e) {
      e.stopPropagation();
      focusClassName = e.target.className;

      /* document.removeEventListener('touchmove', touchMoveLogin);
      document.removeEventListener('touchend', touchEndLogin);

      document.removeEventListener('touchmove', touchMove);
      document.addEventListener('touchmove', touchMoveLogin, false);
      document.addEventListener('touchend', touchEndLogin, false); */
      document.removeEventListener('touchmove', touchMove);
      if (checkDevice() == "android") {
        document.removeEventListener('scroll', scroll);
        document.addEventListener('scroll', scroll, false);
      }

      let offY = Utils.getOffset($(this)[0]).offsetY;
      // window.scrollTo(0, offY - 80);
      setTimeout(function () {
        let viewPortSize = Utils.getViewPortSize();
        let scrollSize = Utils.getScrollOffsets();
        $(".mask").css({
          "height": (viewPortSize.height + scrollSize.scrollY) + "px"
        });
      }, 10);
      if (checkDevice() == "ios") {
        keyboardHide();
      } else {
        window.scrollTo(0, offY - 80);
        androidKeyboard();
      }

    }).on("blur", function (e) {
      blurClassNameArray.push(e.target.className);
    });
    function keyboardHide() {
      if (focusInterval) return false;
      focusInterval = setInterval(function () {
        if (blurClassNameArray.pop() !== focusClassName) return;
        window.scrollTo(0, 0);
        setTimeout(function () {
          let viewPortSize = Utils.getViewPortSize();
          let scrollSize = Utils.getScrollOffsets();
          let loginHeight = $(".login-container").height();
          $(".mask").css({
            "height": (viewPortSize.height + scrollSize.scrollY) + "px"
          });
          $(".login-container").animate({
            "top": ((viewPortSize.height - loginHeight) / 2 + scrollSize.scrollY) + "px"
          }, 50);

          document.removeEventListener('touchmove', touchMove);

          document.addEventListener('touchmove', touchMove, false);
          document.removeEventListener('touchmove', touchMoveLogin);
          document.removeEventListener('touchend', touchEndLogin);
          document.removeEventListener('scroll', scroll);
          if (focusInterval) {
            clearInterval(focusInterval);
            focusInterval = null;
          }
        }, 0);
      }, 100);
    }
    let interval = null;
    let keybordHeight = 0;
    function androidKeyboard() {
      if (interval) return false;
      if (checkDevice() == "android") {
        interval = setInterval(function () {
          setTimeout(function () {
            (async function () {
              let keybordHeight1 = await getKeyborderHeight();
              if (keybordHeight1 <= 0) {
                window.scrollTo(0, 0);
                let viewPortSize = Utils.getViewPortSize();
                let scrollSize = Utils.getScrollOffsets();
                let loginHeight = $(".login-container").height();
                $(".mask").css({
                  "height": (viewPortSize.height + scrollSize.scrollY) + "px"
                });
                $(".login-container").animate({
                  "top": ((viewPortSize.height - loginHeight) / 2 + scrollSize.scrollY) + "px"
                }, 50);
                if (interval) {
                  clearInterval(interval);
                  interval = null;
                  document.removeEventListener('touchmove', touchMove);
                  document.removeEventListener('touchmove', touchMoveLogin);
                  document.removeEventListener('touchend', touchEndLogin);
                  document.removeEventListener('scroll', scroll);

                  document.addEventListener('touchmove', touchMove, false);
                  $("#user-name,#user-pwd").blur();
                }
              }
            })();
          }, 500);
        }, 100);
      }
    }
    async function getKeyborderHeight() {
      let viewPortSize = Utils.getViewPortSize();
      let scrollSize = Utils.getScrollOffsets();
      let tempKeybordHeight = _this.viewPortSizeHeight - viewPortSize.height;
      if (tempKeybordHeight == keybordHeight) {
        return tempKeybordHeight;
      }
      keybordHeight = tempKeybordHeight;
      getKeyborderHeight();
    }
    //关闭login弹出框
    $(".login-close").off().on("click", function () {
      //this.body.delegate(".login-close", "click", function () {
      document.removeEventListener('touchmove', touchMove);
      if (interval) {
        clearInterval(interval);
        interval = null;
      }
      if (focusInterval) {
        clearInterval(focusInterval);
        focusInterval = null;
      }
      _this.disableScroll = false;
      _this.isLogin = true;
      $(".login-container").remove();
      $(".mask").remove();
    });
    //登录
    $(".btn-login").off().on("click", async function () {
      //this.body.delegate(".btn-login", "click", async function () {
      //基本的校验校验密码 跟用户名
      let regExpUserName = /^1[34578]\d{9}$/gi;
      let regExpUserPwd = /\w{6,}/gi;
      let isCheck = true;
      if (!$.trim($("#user-name").val()) && !$.trim($("#user-pwd").val())) {
        isCheck = false;
      }
      if (!$.trim($("#user-name").val()) && $.trim($("#user-pwd").val())) {
        $("#user-name").closest(".form-box").find(".error").text("请输入正确的手机号").removeClass("hide");
        isCheck = false;
      }
      if ($.trim($("#user-pwd").val()) && !regExpUserPwd.test($("#user-pwd").val())) {
        $("#user-pwd").closest(".form-box").find(".error").text("请输入正确的密码").removeClass("hide");
        isCheck = false;
      }
      if (!isCheck) return false;
      //调用登录接口
      let result = await galleryService.doLogin({
        user_name: $("#user-name").val(),
        password: $("#user-pwd").val(),
        user: _this.data.user,
        user_open_id: window.USER_OPEN_ID
      });

      if (result.code == 200) {
        //跳转到会本详情(视频播放页)
        window.location.reload();
      } else {
        //弹层提示
        let dialog = new Dialog(result.message, true);
        let viewPortSize = Utils.getViewPortSize();
        let scrollSize = Utils.getScrollOffsets();
        dialog.location = {
          viewPortSize: viewPortSize,
          scrollSize: scrollSize
        };
      }
    });
  }
  render() {
    this.body.append(this.complied({
      isLogin: this.isLogin,
      registerUrl: this.data.registerUrl
    }));
    let viewPortSize = Utils.getViewPortSize();
    let scrollSize = Utils.getScrollOffsets();
    //let location = this.data.location;
    this.viewPortSizeHeight = viewPortSize.height;
    let viewPortSizeHeight = viewPortSize.height;
    let scrollY = scrollSize.scrollY;
    // if (checkDevice() == "ios")
    //   $(".mask").css({
    //     "position": "absolute",
    //     "height": (viewPortSizeHeight + scrollY) + "px"
    //   });
    $(".login-container").css({
      "top": ((viewPortSizeHeight - $(".login-container").height()) / 2 + scrollY) + "px"
    });
  }
  get location() {

  }
  set location(value) {
    /*  $(".mask").css({
       "height": (value.viewPortSize.height + value.scrollSize.scrollY + 20) + "px"
     }); */
  }
}

let checkDevice = function () {
  let u = navigator.userAgent;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
  let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端 
  if (isAndroid) return "android";
  if (isiOS) return "ios";
  return "";
};